package org.jie.guider.network.netty.echo;

import java.util.concurrent.TimeUnit;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @author LiJie
 */
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object data)
        throws Exception {
        System.out.println("read");
        ByteBuf in = ((ByteBuf) data);
        byte[] bs = ByteBufUtil.getBytes(in);

        String msg = in.toString(CharsetUtil.UTF_8);
        System.out.println(msg);
        TimeUnit.SECONDS.sleep(Integer.parseInt(msg));

        ByteBuf out =
            Unpooled.wrappedBuffer((msg + "收到").getBytes(CharsetUtil.UTF_8));
        ctx.write(out);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx)
        throws Exception {
        System.out.println("read complete");
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
    }
}
